package cn.bdqn.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 工具类
 * 获取SqlSession连接
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //设置要读取的配置文件
            String resource = "mybatis-config.xml";

            //读取配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);

            //获取SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession连接
    public static SqlSession getSqlSession(){
        //参数为true  设置为自动提交事务
        return sqlSessionFactory.openSession(true);
    }
}
